package com.example.netdemo.retrofit;

import android.text.TextUtils;

import com.example.netdemo.base.Constant;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitManager {
    private static final int TIME_OUT = 10;
    private static volatile RetrofitManager instance;
    private OkHttpClient okHttpClient;
    private Map<String, Retrofit> retrofitMap = new ConcurrentHashMap<>();
    private volatile String baseUrl;
    private RetrofitManager() {
        initOkHttp();
    }

    public static RetrofitManager get() {
        if (instance == null) {
            synchronized (RetrofitManager.class) {
                if (instance == null) {
                    instance = new RetrofitManager();
                }
            }
        }
        return instance;
    }

    private void initOkHttp() {
        okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new HeaderInterceptor())
                .addInterceptor(new HttpLogInterceptor())
                .addInterceptor(new TokenInterceptor())
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                //设置整个请求（包括连接、请求、响应）的最大执行时间。优先级最高，会覆盖所有其他超时设置总和
                .callTimeout(TIME_OUT * 6, TimeUnit.SECONDS)
                .build();
    }

    public <T> T create(Class<T> mClazz) {
        return create(mClazz, null);
    }
    public <T> T create(Class<T> mClazz, String baseUrl) {
        this.baseUrl = TextUtils.isEmpty(baseUrl) ? Constant.BASE_URL : baseUrl;

        if (!retrofitMap.containsKey(this.baseUrl)) {
            createRetrofit(this.baseUrl);
        }
        return retrofitMap.get(this.baseUrl).create(mClazz);
    }

    private void createRetrofit(String baseUrl) {
        //双重判断，避免多线程并发重复创建
        if (retrofitMap.containsKey(baseUrl)) return;
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();
        retrofitMap.put(baseUrl, retrofit);
    }

}
